package nccloud.arap.bill.caldisc.action;

import java.util.Collection;

import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.vo.arap.caltradisc.AggCalDiscVO;
import nc.vo.arap.caltradisc.CalDiscVO;
import nc.vo.pf.pub.util.SQLUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nccloud.arap.bill.caldisc.bill.bean.BillOperatorParam;
import nccloud.arap.bill.caldisc.bill.util.CommonUtil;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.ui.pattern.billcard.BillCardOperator;
import nccloud.vo.arap.bill.CalDiscConst;

public class CalDiscAddPzAction implements ICommonAction {

	@Override
	public Object doAction(IRequest paramIRequest) {
		
		BillOperatorParam operaParam = this.getRequestParam(paramIRequest);
		
		AggCalDiscVO[] operaVOs = null;
		AggCalDiscVO vo = null;
		try {
			operaVOs = this.queryBillsByPks(operaParam);
			CalDiscVO headvo = operaVOs[0].getParentVO();
			
			UFDate busidate = new UFDate(headvo.getCperiod() +"-01");
			
			vo = CommonUtil.getFinancingcostMaintainService().genVoucher(operaVOs[0], busidate);
		} catch (BusinessException e) {
			ExceptionUtils.wrapException(e);
		}
		
		BillCardOperator billCardOperator = new BillCardOperator();
		Object billcard = billCardOperator.toCard(vo);
	    // 4、返回结果到前端
	    return billcard;
	    
	}

	protected BillOperatorParam getRequestParam(IRequest request) {
	    // 解析request
	    String str = request.read();
	    IJson json = JsonFactory.create();
	    BillOperatorParam operaParam = json.fromJson(str, BillOperatorParam.class);
	    return operaParam;
	  }
	    
    protected AggCalDiscVO[] queryBillsByPks(BillOperatorParam operaParam)
            throws BusinessException {
      AggCalDiscVO[] vos = null;
      String[] pks = operaParam.getPks();
      if (pks.length != 0) {
        // 根据参数查询结果
        IMDPersistenceQueryService service =
                CommonUtil.getMDPersistenceQueryService();
        String wheresql = SQLUtil
                .buildSqlForIn(CalDiscConst.CONST_PARENT_PRIMARYKEY, pks);
        Collection<AggCalDiscVO> bills = service.queryBillOfVOByCond(
           AggCalDiscVO.class, wheresql, true, false);
        if ((bills == null) || (bills.size() != pks.length)) {
          ExceptionUtils.wrapBusinessException("单据已被修改，请刷新页面后重试");
        }
        vos = bills.toArray(new AggCalDiscVO[0]);
      }
      return vos;
    }
}
